package com.cygsunri.wind.api;

import com.alibaba.fastjson.JSON;
import com.cygsunri.common.constant.DataName;
import com.cygsunri.common.constant.DeviceType;
import com.cygsunri.common.entity.DeviceInfo;
import com.cygsunri.common.service.CommonDataService;
import com.cygsunri.measurement.calculate.AbstractComplexEndureCalculateService;
import com.cygsunri.measurement.entity.Flag;
import com.cygsunri.measurement.entity.MeasurementValue;
import com.cygsunri.scada.base.BasePSR;
import com.cygsunri.scada.service.ScadaPSRService;
import com.cygsunri.util.DateUtil;
import com.cygsunri.util.TimeUtil;
import com.cygsunri.wind.config.WindCurveConfig;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Line;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 风电页api
 */
@RestController
@RequestMapping("/api/wind")
public class WindController {
    @Value("${corsair.yc.step}")
    private Integer ycStep;

    @Autowired
    private CommonDataService commonDataService;

    @Autowired
    private ScadaPSRService scadaPSRService;

    @Autowired
    private AbstractComplexEndureCalculateService abstractComplexEndureCalculateService;

    @Autowired
    private WindCurveConfig windCurveConfig;

    /**
     * 风电功率曲线
     *
     * @param id 风电PSRID
     * @param date yyyy-mm-dd
     */
    @RequestMapping(value = "/charts/substations/{id}/power/{date}", method = RequestMethod.GET)
    public ResponseEntity<String> solarPower(@PathVariable("id") String id, @PathVariable("date") String date) {
        Option option = new Option();
        CategoryAxis categoryAxis = new CategoryAxis();
        option.xAxis(categoryAxis);

        Line power1 = new Line("风机逆变器1");
        option.series(power1);

        Line power2 = new Line("风机逆变器2");
        option.series(power2);

        List<BasePSR> inverters = scadaPSRService.getDeviceOfSubstationByType(id, DeviceType.INVERTER.getKey());
        BasePSR inverter1 = inverters.get(0);
        List<MeasurementValue> power1Values = commonDataService.getHistoryValue(inverter1.getId(), DataName.OUT_POWER, date.trim() + " 00:00", date.trim() + " 24:00", ycStep, 2, false);
        if (!power1Values.isEmpty()) {
            for (MeasurementValue outPower : power1Values) {
                if (categoryAxis.getData() == null || categoryAxis.getData().size() < 288 ) {
                    categoryAxis.data(outPower.getTime());
                }
                power1.data(outPower.isInValid() ? "-" : outPower.getData());
            }
        }

        BasePSR inverter2 = inverters.get(1);
        List<MeasurementValue> power2Values = commonDataService.getHistoryValue(inverter2.getId(), DataName.OUT_POWER, date.trim() + " 00:00", date.trim() + " 24:00", ycStep, 2, false);
        if (!power2Values.isEmpty()) {
            for (MeasurementValue outPower : power2Values) {
                if (categoryAxis.getData() == null || categoryAxis.getData().size() < 288 ) {
                    categoryAxis.data(outPower.getTime());
                }
                power2.data(outPower.isInValid() ? "-" : outPower.getData());
            }
        }
//        List<MeasurementValue> powerValues = commonDataService.getHistoryValue(id, DataName.TOTAL_ACTIVE_POWER, windCurveConfig.buildBeginTime(date), windCurveConfig.buildEndTime(date), ycStep, 2, false);
//        boolean hasX = false;
//        if (!powerValues.isEmpty()) {
//            hasX = true;
//            for (MeasurementValue outPower : powerValues) {
//                categoryAxis.data(outPower.getTime());
//                power.data(outPower.isInValid() ? "-" : outPower.getData());
//            }
//        }
        return new ResponseEntity<>(JSON.toJSONString(option), HttpStatus.OK);
    }

    /**
     * 逆变器运行状态
     *
     * @param id 风电PSRID
     */
    @RequestMapping(value = "/statistics/substations/{id}/inverters", method = RequestMethod.GET)
    public ResponseEntity<List<DeviceInfo>> invertersInfo(@PathVariable("id") String id) {
        List<DeviceInfo> deviceInfoList = new ArrayList<>();
        List<BasePSR> inverters = scadaPSRService.getDeviceOfSubstationByType(id, DeviceType.INVERTER.getKey());
        for (BasePSR inverter : inverters) {
            ImmutablePair<String, String> pair = abstractComplexEndureCalculateService.getDeviceStatusPair(inverter.getId());
            DeviceInfo deviceInfo = new DeviceInfo()
                    .setPsrID(inverter.getId())
                    .setName(inverter.getName())
                    .setType(DeviceType.INVERTER.getName())
                    .setStatus(pair == null ? null : pair.getRight());

            List<Map<String, String>> list = new ArrayList<>();

            MeasurementValue outPower = commonDataService.getValue(inverter.getId(), DataName.OUT_POWER);
            MeasurementValue dayGenerated = commonDataService.getValue(inverter.getId(), DataName.DAY_GENERATED);

            Map<String, String> m1 = Maps.newHashMap();
            m1.put("name", DataName.OUT_POWER);
            m1.put("data", outPower.isInValid() ? "-" : String.valueOf(outPower.getData()));
            list.add(m1);

            Map<String, String> m2 = Maps.newHashMap();
            m2.put("name", DataName.DAY_GENERATED);
            m2.put("data", dayGenerated.isInValid() ? "-" : String.valueOf(dayGenerated.getData()));
            list.add(m2);

            deviceInfo.setExtra(list);
            deviceInfoList.add(deviceInfo);
        }

        return new ResponseEntity<>(deviceInfoList, HttpStatus.OK);
    }

    /**
     * 逆变器发电量对比
     *
     * @param type Day/Month/Year
     * @param date yyyy-mm-dd/yyyy-mm/yyyy
     */
    @RequestMapping(value = "/invertersKwh/substations/{id}/{type}/{date}", method = RequestMethod.GET)
    public ResponseEntity<String> invertersKwh(@PathVariable("id") String id, @PathVariable("type") String type, @PathVariable("date") String date) {
        Option option = new Option();
        CategoryAxis categoryAxis = new CategoryAxis();
        option.xAxis(categoryAxis);
        List<String> dates = Lists.newArrayList();
        Integer flag;
        switch (type) {
            case "Day":
                dates = DateUtil.getHours(windCurveConfig.buildBeginTime(date), windCurveConfig.buildEndTime(date));
                flag = Flag.HOUR_DIFF;
                break;
            case "Month":
                dates = DateUtil.getDays(date);
                flag = Flag.DAY_DIFF;
                break;
            case "Year":
                dates = DateUtil.getMonths(date);
                flag = Flag.MONTH_DIFF;
                break;
            default:
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        List<BasePSR> inverters = scadaPSRService.getDeviceOfSubstationByType(id, DeviceType.INVERTER.getKey());
        int first = 0;
        for (BasePSR inverter : inverters) {
            Bar bar = new Bar(inverter.getName());
            option.series(bar);
            for (String d : dates) {
                if (first == 0) {
                    categoryAxis.data(d);
                }
                MeasurementValue m = commonDataService.getValue(inverter.getId(), DataName.TOTAL_GENERATED, TimeUtil.toMilliSeconds(d), flag);
                bar.data(m.isInValid() ? "-" : m.getData());
            }
            first++;
        }
        return new ResponseEntity<>(JSON.toJSONString(option), HttpStatus.OK);
    }
}
